<template>
  <div class="user-list-container">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="转账id">
            <el-input
              v-model="searchForm.TransferId"
              placeholder="请输入转账id"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="转出卡id">
            <el-input
              v-model="searchForm.FromCardId"
              placeholder="请输入转出卡id"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="转出完整卡号">
            <el-input
              v-model="searchForm.FromCompleteCardNumber"
              placeholder="请输入转出完整卡号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="转入卡id">
            <el-input
              v-model="searchForm.ToCardId"
              placeholder="请输入转入卡id"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="转入完整卡号">
            <el-input
              v-model="searchForm.ToCompleteCardNumber"
              placeholder="请输入转入完整卡号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="商户">
            <el-select
              v-model="searchForm.MerchantId"
              placeholder="请选择商户"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in merchantIdOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 商户表格 -->
      <el-table 
        :data="list" 
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        empty-text="暂无数据"
      >
        <el-table-column prop="CardTransferId" label="转账id" width="180">
          <template #default="scope">
            <div class="copy-cell">
              <el-tooltip :content="scope.row.CardTransferId" placement="top">
                <span class="text-ellipsis">{{ scope.row.CardTransferId }}</span>
              </el-tooltip>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.CardTransferId, '转账id')"
                class="copy-btn"
                v-if="scope.row.CardTransferId"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="FromCardId" label="转出卡id" width="180">
          <template #default="scope">
            <div class="copy-cell">
              <el-tooltip :content="scope.row.FromCardId" placement="top">
                <span class="text-ellipsis">{{ scope.row.FromCardId }}</span>
              </el-tooltip>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.FromCardId, '转出卡id')"
                class="copy-btn"
                v-if="scope.row.FromCardId"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="FromCardNumber" label="转出卡号" show-overflow-tooltip width="150"/>
        <!-- <el-table-column prop="FromCard" label="转出持卡人id" show-overflow-tooltip width="150">
          <template #default="scope">
            <span>{{ scope.row.FromCard?.CardholderId }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="ToCardId" label="转入卡id" width="180">
          <template #default="scope">
            <div class="copy-cell">
              <el-tooltip :content="scope.row.ToCardId" placement="top">
                <span class="text-ellipsis">{{ scope.row.ToCardId }}</span>
              </el-tooltip>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.ToCardId, '转入卡id')"
                class="copy-btn"
                v-if="scope.row.ToCardId"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="ToCardNumber" label="转入卡号" show-overflow-tooltip width="150"/>
        <!-- <el-table-column prop="ToCard" label="转入持卡人id" show-overflow-tooltip width="150">
          <template #default="scope">
            <span>{{ scope.row.ToCard?.CardholderId }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="Amount" label="转账金额" show-overflow-tooltip width="150"/>
        <el-table-column prop="StatusString" label="状态" show-overflow-tooltip width="150"/>
        <el-table-column prop="Merchant" label="商户名称" show-overflow-tooltip width="150">
          <template #default="scope">
            <span>{{ scope.row.Merchant?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="MerchantAccountId" label="商户id" width="180">
          <template #default="scope">
            <div class="copy-cell">
              <el-tooltip :content="scope.row.MerchantAccountId" placement="top">
                <span class="text-ellipsis">{{ scope.row.MerchantAccountId }}</span>
              </el-tooltip>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.MerchantAccountId, '商户id')"
                class="copy-btn"
                v-if="scope.row.MerchantAccountId"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="UpstreamPlatform" label="上游平台名称" width="120" >
          <template #default="scope">
            <span>{{ scope.row.UpstreamPlatform?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UpstreamPlatformId" label="上游平台id" width="150" />
        <el-table-column prop="CreatedAtString" label="创建时间" sortable show-overflow-tooltip width="120" />
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import { cardTransferList } from '@/api/card'
import { upstreamPlatformList, merchantList, cardStatusList } from '@/api/selectList'

// 响应式数据
const loading = ref(false)
const list = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const merchantIdOptions = ref([])
const cardStatusOptions = ref([])
const dateRange = ref([])
const cardFormFactorOptions = ref([
  {
    label: '虚拟卡',
    value: 'VIRTUAL',
  },
  {
    label: '实体卡',
    value: 'PHYSICAL',
  },
])
// 搜索表单
const searchForm = reactive({
  ToCardId: '',
  ToCompleteCardNumber: '',
  TransferId: '',
  FromCardId: '',
  FromCompleteCardNumber: '',
  MerchantId: '',
})

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await cardTransferList({
      ...searchForm,
      Page: currentPage.value,
      PageSize: pageSize.value,
    })
    if (res.code === 200) {
      list.value = res.data?.List || []
      total.value = res.data?.Total
    } else {
      ElMessage.error('获取列表失败')
    }
  } catch (error) {
    // ElMessage.error('获取商户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const handleReset = () => {
  dateRange.value = []
  Object.assign(searchForm, {
    ToCardId: '',
    ToCompleteCardNumber: '',
    TransferId: '',
    FromCardId: '',
    FromCompleteCardNumber: '',
    MerchantId: '',
  })
  currentPage.value = 1
  getList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  getList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  getList()
}

const getMerchantIdOptions = async () => {
  try {
    const res = await merchantList()
    if (res.code === 200) {
      merchantIdOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

// 生命周期
onMounted(() => {
  getList()
  getMerchantIdOptions()
})

// 日期范围选择器 - 禁用日期逻辑
const disabledDate = (time) => {
  // 如果已经选择了开始日期,限制结束日期在开始日期的前后90天内
  if (dateRange.value && dateRange.value.length > 0 && dateRange.value[0]) {
    const startTime = new Date(dateRange.value[0]).getTime()
    const currentTime = time.getTime()
    const dayDiff = Math.abs((currentTime - startTime) / (1000 * 60 * 60 * 24))
    // 禁用超过90天的日期
    return dayDiff > 90
  }
  
  return false
}

// 日期范围变化处理
const handleDateChange = (value) => {
  if (value && value.length === 2) {
    const [startTime, endTime] = value
    const start = new Date(startTime)
    const end = new Date(endTime)
    const dayDiff = Math.abs((end - start) / (1000 * 60 * 60 * 24))
    
    if (dayDiff > 90) {
      ElMessage.warning('日期范围不能超过90天')
      dateRange.value = []
      searchForm.StartTime = ''
      searchForm.EndTime = ''
      return
    }
    
    searchForm.StartTime = startTime
    searchForm.EndTime = endTime
  } else {
    searchForm.StartTime = ''
    searchForm.EndTime = ''
  }
}

// 复制功能
const handleCopy = async (text, fieldName) => {
  try {
    if (!text) {
      ElMessage.warning('复制内容为空')
      return
    }
    
    // 使用现代浏览器的 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      ElMessage.success(`${fieldName}复制成功`)
    } else {
      // 降级方案：使用传统的 document.execCommand
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          ElMessage.success(`${fieldName}复制成功`)
        } else {
          ElMessage.error('复制失败')
        }
      } catch (err) {
        ElMessage.error('复制失败')
      }
      
      document.body.removeChild(textArea)
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-table__header-wrapper .cell) {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

/* 复制按钮样式 */
.copy-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.text-ellipsis {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.copy-btn {
  flex-shrink: 0;
  padding: 4px;
  margin: 0;
}

.copy-btn:hover {
  color: var(--el-color-primary);
}

/* 日期选择器样式 */
:deep(.el-date-editor) {
  width: 100%;
}

/* 让表格滚动条始终显示 */
::v-deep(.el-table__body-wrapper .el-scrollbar__bar) {
  display: block!important;
}
:deep(.el-scrollbar__thumb) {
  background-color: #909399;
  opacity: 1;
}
</style>